{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "os.environ['CUDA_VISIBLE_DEVICES'] = '2'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [],
   "source": [
    "import numpy as np\n",
    "import tensorflow as tf\n",
    "import json"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "with open('dataset-bpe.json') as fopen:\n",
    "    data = json.load(fopen)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_X = data['train_X']\n",
    "train_Y = data['train_Y']\n",
    "test_X = data['test_X']\n",
    "test_Y = data['test_Y']"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "EOS = 2\n",
    "GO = 1\n",
    "vocab_size = 32000"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [],
   "source": [
    "train_Y = [i + [2] for i in train_Y]\n",
    "test_Y = [i + [2] for i in test_Y]"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import beam_search\n",
    "\n",
    "def pad_second_dim(x, desired_size):\n",
    "    padding = tf.tile([[[0.0]]], tf.stack([tf.shape(x)[0], desired_size - tf.shape(x)[1], tf.shape(x)[2]], 0))\n",
    "    return tf.concat([x, padding], 1)\n",
    "\n",
    "class Translator:\n",
    "    def __init__(self, size_layer, num_layers, embedded_size, learning_rate,\n",
    "                beam_width = 5):\n",
    "        \n",
    "        def cells(size_layer = size_layer, reuse=False):\n",
    "            return tf.nn.rnn_cell.GRUCell(size_layer, reuse=reuse)\n",
    "        \n",
    "        def attention(encoder_out, seq_len, reuse=False):\n",
    "            attention_mechanism = tf.contrib.seq2seq.LuongMonotonicAttention(num_units = size_layer, \n",
    "                                                                    memory = encoder_out,\n",
    "                                                                    memory_sequence_length = seq_len)\n",
    "            return tf.contrib.seq2seq.AttentionWrapper(\n",
    "            cell = tf.nn.rnn_cell.MultiRNNCell([cells(reuse=reuse) for _ in range(num_layers)]), \n",
    "                attention_mechanism = attention_mechanism,\n",
    "                attention_layer_size = size_layer)\n",
    "        \n",
    "        self.X = tf.placeholder(tf.int32, [None, None])\n",
    "        self.Y = tf.placeholder(tf.int32, [None, None])\n",
    "        \n",
    "        self.X_seq_len = tf.count_nonzero(self.X, 1, dtype = tf.int32)\n",
    "        self.Y_seq_len = tf.count_nonzero(self.Y, 1, dtype = tf.int32)\n",
    "        batch_size = tf.shape(self.X)[0]\n",
    "        \n",
    "        embeddings = tf.Variable(tf.random_uniform([vocab_size, embedded_size], -1, 1))\n",
    "        encoder_out = tf.nn.embedding_lookup(embeddings, self.X)\n",
    "        \n",
    "        for n in range(num_layers):\n",
    "            (out_fw, out_bw), (state_fw, state_bw) = tf.nn.bidirectional_dynamic_rnn(\n",
    "                cell_fw = cells(size_layer // 2),\n",
    "                cell_bw = cells(size_layer // 2),\n",
    "                inputs = encoder_out,\n",
    "                sequence_length = self.X_seq_len,\n",
    "                dtype = tf.float32,\n",
    "                scope = 'bidirectional_rnn_%d'%(n))\n",
    "            encoder_out = tf.concat((out_fw, out_bw), 2)\n",
    "        bi_state = tf.concat((state_fw,state_bw), -1)\n",
    "        encoder_state = tuple([bi_state] * num_layers)\n",
    "        \n",
    "        main = tf.strided_slice(self.Y, [0, 0], [batch_size, -1], [1, 1])\n",
    "        decoder_input = tf.concat([tf.fill([batch_size, 1], GO), main], 1)\n",
    "        dense = tf.layers.Dense(vocab_size)\n",
    "        \n",
    "        with tf.variable_scope('decode'):\n",
    "            decoder_cells = attention(encoder_out, self.X_seq_len)\n",
    "            states = decoder_cells.zero_state(batch_size, tf.float32).clone(cell_state=encoder_state)\n",
    "\n",
    "            training_helper = tf.contrib.seq2seq.TrainingHelper(\n",
    "                    inputs = tf.nn.embedding_lookup(embeddings, decoder_input),\n",
    "                    sequence_length = self.Y_seq_len,\n",
    "                    time_major = False)\n",
    "            training_decoder = tf.contrib.seq2seq.BasicDecoder(\n",
    "                    cell = decoder_cells,\n",
    "                    helper = training_helper,\n",
    "                    initial_state = states,\n",
    "                    output_layer = dense)\n",
    "            training_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                    decoder = training_decoder,\n",
    "                    impute_finished = True,\n",
    "                    maximum_iterations = tf.reduce_max(self.Y_seq_len))\n",
    "            self.training_logits = training_decoder_output.rnn_output\n",
    "        \n",
    "        with tf.variable_scope('decode', reuse=True):\n",
    "            encoder_out_tiled = tf.contrib.seq2seq.tile_batch(encoder_out, beam_width)\n",
    "            encoder_state_tiled = tf.contrib.seq2seq.tile_batch(encoder_state, beam_width)\n",
    "            X_seq_len_tiled = tf.contrib.seq2seq.tile_batch(self.X_seq_len, beam_width)\n",
    "            decoder_cell = attention(encoder_out_tiled, X_seq_len_tiled, reuse=True)\n",
    "            states = decoder_cell.zero_state(batch_size * beam_width, tf.float32).clone(\n",
    "                    cell_state = encoder_state_tiled)\n",
    "            predicting_decoder = tf.contrib.seq2seq.BeamSearchDecoder(\n",
    "                cell = decoder_cell,\n",
    "                embedding = embeddings,\n",
    "                start_tokens = tf.tile(tf.constant([GO], dtype=tf.int32), [batch_size]),\n",
    "                end_token = EOS,\n",
    "                initial_state = states,\n",
    "                beam_width = beam_width,\n",
    "                output_layer = dense,\n",
    "                length_penalty_weight = 0.0)\n",
    "            predicting_decoder_output, _, _ = tf.contrib.seq2seq.dynamic_decode(\n",
    "                decoder = predicting_decoder,\n",
    "                impute_finished = False,\n",
    "                maximum_iterations = 2 * tf.reduce_max(self.X_seq_len))\n",
    "            self.fast_result = predicting_decoder_output.predicted_ids[:, :, 0]\n",
    "        \n",
    "        masks = tf.sequence_mask(self.Y_seq_len, tf.reduce_max(self.Y_seq_len), dtype=tf.float32)\n",
    "        self.cost = tf.contrib.seq2seq.sequence_loss(logits = self.training_logits,\n",
    "                                                     targets = self.Y,\n",
    "                                                     weights = masks)\n",
    "        self.optimizer = tf.train.AdamOptimizer(learning_rate = learning_rate).minimize(self.cost)\n",
    "        y_t = tf.argmax(self.training_logits,axis=2)\n",
    "        y_t = tf.cast(y_t, tf.int32)\n",
    "        self.prediction = tf.boolean_mask(y_t, masks)\n",
    "        mask_label = tf.boolean_mask(self.Y, masks)\n",
    "        correct_pred = tf.equal(self.prediction, mask_label)\n",
    "        correct_index = tf.cast(correct_pred, tf.float32)\n",
    "        self.accuracy = tf.reduce_mean(tf.cast(correct_pred, tf.float32))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "size_layer = 512\n",
    "num_layers = 2\n",
    "embedded_size = 256\n",
    "learning_rate = 1e-3\n",
    "batch_size = 128\n",
    "epoch = 20"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/util/deprecation.py:507: calling count_nonzero (from tensorflow.python.ops.math_ops) with axis is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "reduction_indices is deprecated, use axis instead\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:12: GRUCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.GRUCell, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:40: bidirectional_dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.Bidirectional(keras.layers.RNN(cell))`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:464: dynamic_rnn (from tensorflow.python.ops.rnn) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `keras.layers.RNN(cell)`, which is equivalent to this API\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:559: Layer.add_variable (from tensorflow.python.keras.engine.base_layer) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Please use `layer.add_weight` method instead.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:565: calling Constant.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn_cell_impl.py:575: calling Zeros.__init__ (from tensorflow.python.ops.init_ops) with dtype is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Call initializer instance with the dtype argument instead of passing it to the constructor\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/python/ops/rnn.py:244: where (from tensorflow.python.ops.array_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use tf.where in 2.0, which has the same broadcast rule as np.where\n",
      "WARNING:tensorflow:\n",
      "The TensorFlow contrib module will not be included in TensorFlow 2.0.\n",
      "For more information, please see:\n",
      "  * https://github.com/tensorflow/community/blob/master/rfcs/20180907-contrib-sunset.md\n",
      "  * https://github.com/tensorflow/addons\n",
      "  * https://github.com/tensorflow/io (for I/O related ops)\n",
      "If you depend on functionality not listed there, please file an issue.\n",
      "\n",
      "WARNING:tensorflow:From <ipython-input-7-ee1038269df4>:19: MultiRNNCell.__init__ (from tensorflow.python.ops.rnn_cell_impl) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "This class is equivalent as tf.keras.layers.StackedRNNCells, and will be replaced by that in Tensorflow 2.0.\n",
      "WARNING:tensorflow:From /home/husein/.local/lib/python3.6/site-packages/tensorflow_core/contrib/seq2seq/python/ops/beam_search_decoder.py:971: to_int64 (from tensorflow.python.ops.math_ops) is deprecated and will be removed in a future version.\n",
      "Instructions for updating:\n",
      "Use `tf.cast` instead.\n"
     ]
    }
   ],
   "source": [
    "tf.reset_default_graph()\n",
    "sess = tf.InteractiveSession()\n",
    "model = Translator(size_layer, num_layers, embedded_size, learning_rate)\n",
    "sess.run(tf.global_variables_initializer())"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {},
   "outputs": [],
   "source": [
    "pad_sequences = tf.keras.preprocessing.sequence.pad_sequences"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "[array([[25234, 25234, 25234, 25234, 25147, 25147, 25147, 25147, 25147,\n",
       "         19416, 19416,  4777,  4777,  1805,  1805,  1805,  1805,  1805,\n",
       "         28285, 14894, 14894, 14894, 14894, 30741, 30741, 15395, 15395,\n",
       "         28650, 28650, 28650,  1803,  1803,  1803,  1803,  4283,  4283,\n",
       "          4283, 22741, 22741, 22741, 22741, 22741, 13653, 13653, 19923,\n",
       "         11720, 19923, 19923, 19923, 19923, 19923, 19923, 11645, 11645,\n",
       "         11645, 11645, 18418, 18418, 18418, 18418, 18418, 15632, 15632,\n",
       "         15632, 23234, 23234, 23234, 31936, 31936, 31936, 31936, 31936],\n",
       "        [14797, 23849, 23849, 23849, 28739, 18292, 18292, 18292, 18292,\n",
       "         31408,  2628, 12087, 22731, 22731, 22731, 22731, 18471, 18471,\n",
       "          2307,  2307,  2307,  2307,   812,   812,   812,   812,   812,\n",
       "         12616, 12616, 12616, 12616, 12616, 12616, 12616,  3091,  3091,\n",
       "          3091, 15589, 21929, 21929,  3654,  3654,  3654,  3654,  3654,\n",
       "          3654,  3654, 24059, 24059, 24059, 24059, 21467, 21467, 21467,\n",
       "         21467, 21467, 21467, 21467, 21467, 18344, 23832, 23832, 23832,\n",
       "         23832, 23832, 23832, 23832, 23832, 23832, 23832, 27046, 30740],\n",
       "        [14848, 14848,  7332,  7332, 28455, 28455, 28455,  3283,  3283,\n",
       "          2013,  2013,  2013,  2013,  2013,  2013,  2013,  4850,  4850,\n",
       "          4850,  4850, 16852, 16852, 16852, 16852, 17203, 25066, 25066,\n",
       "         25066,  7375, 10444, 18465, 10444, 19552, 12758, 12758, 12758,\n",
       "         12758, 30175, 30175, 30175, 17616, 17616, 17616, 23678,   940,\n",
       "           940, 23678, 13394, 13394, 13394, 13394, 13394, 13394, 13394,\n",
       "         13394, 21408, 21408, 21408, 21408, 21408, 21408, 18068, 18068,\n",
       "         18068, 29317, 29321, 29321, 29321, 29321, 29321,   370,   370],\n",
       "        [24120, 27115, 27115, 27115,  9553, 29103, 29103, 29103, 29103,\n",
       "         29103, 29103, 29103, 29103, 29103, 29103,  7682,  7682,  7682,\n",
       "          7682,  7682,  7682,  7682, 17343, 28744,  1320,  3740,  1320,\n",
       "          3740,  3740,  3740,  3740,  3740,  3740,  3740, 10404, 10404,\n",
       "         23672, 21159, 21159, 21159, 21159, 21159, 11806,  9787,  9787,\n",
       "          9787, 13756, 13756, 13756, 13756, 13756, 13756, 13756,  3411,\n",
       "          3411,  3411, 15244, 15244, 15244, 15244, 15244, 15244, 15244,\n",
       "          1383,  1383, 24905, 24905, 24905, 24905, 24905, 18580, 15406],\n",
       "        [26720, 24727, 24727, 24727, 30888, 30888, 30888, 30888, 30888,\n",
       "         25127, 24731, 21808, 21808, 21808, 21808,  5687,  5687,  5687,\n",
       "          5687,  5687,  5687,  4290,  4290,  4290,  4290, 26784, 26784,\n",
       "         26784, 26784,  8646,  8646,  8646, 24987, 24987, 24987, 26429,\n",
       "         26429, 19665, 19665, 19665, 19665, 20132, 20132, 19025, 19025,\n",
       "         19025, 31997, 15658,  4507,  4507,  4507,  4507, 20698, 20698,\n",
       "         20698, 20698, 20698,  3458,  3458,  3458, 30088, 30088, 13561,\n",
       "         28484, 13561, 13561,  4802, 11670, 11670, 20468, 20468, 11857],\n",
       "        [ 2897,  2897,  3903, 16822, 16822, 16822, 12873, 12873, 12873,\n",
       "         28086, 28086, 28086, 28086, 17142, 17142, 17142, 17142,  4315,\n",
       "          4315,  4315,  5000,  5000,  5000,  5000, 17839, 17839,  6157,\n",
       "          3057,  3057,  8726,  8726,  8726, 27976, 27976, 27976, 27976,\n",
       "         27976, 16212, 17763, 17763, 17763, 17763, 17763, 17763, 30227,\n",
       "         30109, 30109, 30109, 30109,  4367,  1336,  1336,  1336,  1336,\n",
       "          1336,  1336,  1336,  1336, 27333, 27333, 27333, 27333, 27333,\n",
       "         27333, 18762, 25608, 25608, 25608, 25608, 25608, 18762, 26089],\n",
       "        [ 7373,  7373,  7373, 10320, 10320, 10320,   730,   730,   730,\n",
       "          6795, 22740, 22740, 22740, 22740, 22740, 22740, 24252, 24252,\n",
       "         24252,  7706,  7706,  7706, 18645, 18645,  5131,  5131,  5131,\n",
       "         23748,  1972,  1972,  1972,  6099,  6099,  1386,  1386,  7538,\n",
       "          7538,   370,   370,   370,   370,   370, 20606, 20606, 20606,\n",
       "         20606, 20606, 21380, 21380, 21380, 21380, 21380, 21380, 15450,\n",
       "         15450,  8617,  8617,  8617, 15360, 15360, 30902, 30902, 12284,\n",
       "         12284, 12284, 12284, 16301, 16301, 16301, 16301, 16301, 16301],\n",
       "        [21004, 10456, 10456, 10456,  6483,  6483, 14991, 14991, 25902,\n",
       "          3927,  3927,  3927,  3927,  5534,  5534,  5534,  5534,  8793,\n",
       "           856,   856,   856,  7059,  7059,  7059,  7059,  7059, 19732,\n",
       "         19732, 11877, 11877, 11877,  3492,  3492,  3492,   387,   387,\n",
       "           387,  6076,  6076,  6076,  6076, 25249, 25249,   904,  1026,\n",
       "          1026,  1026,  1026,  1026,  1026,  1026, 15494, 15494, 15494,\n",
       "          1725,  1725,  1725,  1725, 12929, 12929, 12929, 12929, 12929,\n",
       "         23991, 23991, 23991, 19689, 19689, 19689,  7579, 12843, 12843],\n",
       "        [13979, 13979,  7112,  7112,  7112,  7112,  7112,  7112,  5904,\n",
       "          5904,  5904,  8328,  8328,  8328,  8328,  8328,  8328, 10453,\n",
       "         27401,  8803,  8803,  8803,  8795, 20232, 20232, 20232, 20232,\n",
       "         20232, 10088, 10088, 20232, 20232, 20232, 20232, 20232,  1934,\n",
       "          1934,  1934, 19639, 19639, 12584, 12584, 12584, 12584, 12584,\n",
       "         12584, 13290, 13290, 13290, 13290, 19151, 19151, 19151, 19151,\n",
       "         19151,  6545, 23261, 23261, 30768, 30768, 30768, 25014, 28074,\n",
       "         25014, 25014, 25014,  1222,  1222, 20054, 20054,  9242,  9242],\n",
       "        [11013, 11013,  9679,  5892,   328,   328,   328,   328,   328,\n",
       "          2751,  2751,  2751,  5538,  5538,  2199,  3244,  3244,  3244,\n",
       "          3244,  3244, 28821, 28821,  5214,  5214,  5214,  5214,  5214,\n",
       "         31146,  5218,  5218,  5218,  5218,  5218,  5218,  4383,  4383,\n",
       "          4383,  4383, 27831, 27831, 29018, 29018, 24237, 27614, 27614,\n",
       "         27614,  6158,  6158,  6158,  6158,  6158,  6158, 11853, 11853,\n",
       "         11853, 25252, 25252, 26890, 26890, 26890, 22828, 22828, 22828,\n",
       "           682,   682,   682,   682, 15504, 15504, 15504, 15504, 23702]],\n",
       "       dtype=int32), 10.374842, 0.0]"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "batch_x = pad_sequences(train_X[:10], padding='post')\n",
    "batch_y = pad_sequences(train_Y[:10], padding='post')\n",
    "\n",
    "sess.run([model.fast_result, model.cost, model.accuracy], \n",
    "         feed_dict = {model.X: batch_x, model.Y: batch_y})"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:11<00:00,  1.84it/s, accuracy=0.24, cost=4.8]  \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.81it/s, accuracy=0.29, cost=4.02] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 1, training avg loss 5.508914, training avg acc 0.189940\n",
      "epoch 1, testing avg loss 4.582977, testing avg acc 0.252679\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:09<00:00,  1.84it/s, accuracy=0.308, cost=3.87]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.88it/s, accuracy=0.349, cost=3.65]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 2, training avg loss 4.071308, training avg acc 0.302255\n",
      "epoch 2, testing avg loss 3.953419, testing avg acc 0.318366\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  71%|███████▏  | 1117/1563 [10:03<03:34,  2.08it/s, accuracy=0.298, cost=3.96]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.425, cost=2.79]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.89it/s, accuracy=0.323, cost=3.26]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 5, training avg loss 3.170784, training avg acc 0.382714\n",
      "epoch 5, testing avg loss 3.649862, testing avg acc 0.347600\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  34%|███▍      | 538/1563 [04:50<10:48,  1.58it/s, accuracy=0.393, cost=3.08]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:09<00:00,  1.84it/s, accuracy=0.524, cost=2.11]\n",
      "minibatch loop:   2%|▎         | 1/40 [00:00<00:16,  2.35it/s, accuracy=0.358, cost=3.67]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:11<00:00,  1.83it/s, accuracy=0.55, cost=1.96] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.87it/s, accuracy=0.366, cost=3.32]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 10, training avg loss 2.361690, training avg acc 0.490355\n",
      "epoch 10, testing avg loss 3.648373, testing avg acc 0.369710\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  53%|█████▎    | 833/1563 [07:31<05:56,  2.05it/s, accuracy=0.509, cost=2.23]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:09<00:00,  1.84it/s, accuracy=0.616, cost=1.64]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.85it/s, accuracy=0.403, cost=3.27]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 13, training avg loss 2.152935, training avg acc 0.518422\n",
      "epoch 13, testing avg loss 3.753027, testing avg acc 0.368115\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop:  11%|█▏        | 177/1563 [01:34<11:39,  1.98it/s, accuracy=0.534, cost=2.05]IOPub message rate exceeded.\n",
      "The notebook server will temporarily stop sending output\n",
      "to the client in order to avoid crashing it.\n",
      "To change this limit, set the config variable\n",
      "`--NotebookApp.iopub_msg_rate_limit`.\n",
      "\n",
      "Current values:\n",
      "NotebookApp.iopub_msg_rate_limit=1000.0 (msgs/sec)\n",
      "NotebookApp.rate_limit_window=3.0 (secs)\n",
      "\n",
      "minibatch loop: 100%|██████████| 1563/1563 [14:09<00:00,  1.84it/s, accuracy=0.611, cost=1.63]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.86it/s, accuracy=0.371, cost=3.47]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 15, training avg loss 2.059179, training avg acc 0.530841\n",
      "epoch 15, testing avg loss 3.899434, testing avg acc 0.358237\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.64, cost=1.48] \n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.398, cost=3.43]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 16, training avg loss 2.031732, training avg acc 0.533531\n",
      "epoch 16, testing avg loss 3.936462, testing avg acc 0.360117\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.623, cost=1.53]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.93it/s, accuracy=0.344, cost=3.7] \n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 17, training avg loss 2.009967, training avg acc 0.535448\n",
      "epoch 17, testing avg loss 4.016814, testing avg acc 0.350279\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:08<00:00,  1.84it/s, accuracy=0.645, cost=1.46]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.85it/s, accuracy=0.349, cost=3.71]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 18, training avg loss 1.964343, training avg acc 0.542473\n",
      "epoch 18, testing avg loss 4.075366, testing avg acc 0.349923\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 1563/1563 [14:10<00:00,  1.84it/s, accuracy=0.661, cost=1.39]\n",
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.92it/s, accuracy=0.344, cost=3.86]\n",
      "minibatch loop:   0%|          | 0/1563 [00:00<?, ?it/s]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 19, training avg loss 1.915232, training avg acc 0.550734\n",
      "epoch 19, testing avg loss 4.160676, testing avg acc 0.348705\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "minibatch loop: 100%|██████████| 40/40 [00:10<00:00,  3.90it/s, accuracy=0.333, cost=3.96].85]"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "epoch 20, training avg loss 1.861063, training avg acc 0.560226\n",
      "epoch 20, testing avg loss 4.265983, testing avg acc 0.342945\n"
     ]
    },
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\n"
     ]
    }
   ],
   "source": [
    "import tqdm\n",
    "\n",
    "for e in range(epoch):\n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(train_X), batch_size), desc = 'minibatch loop')\n",
    "    train_loss, train_acc, test_loss, test_acc = [], [], [], []\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(train_X))\n",
    "        batch_x = pad_sequences(train_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(train_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y}\n",
    "        accuracy, loss, _ = sess.run([model.accuracy,model.cost,model.optimizer],\n",
    "                                    feed_dict = feed)\n",
    "        train_loss.append(loss)\n",
    "        train_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    \n",
    "    pbar = tqdm.tqdm(\n",
    "        range(0, len(test_X), batch_size), desc = 'minibatch loop')\n",
    "    for i in pbar:\n",
    "        index = min(i + batch_size, len(test_X))\n",
    "        batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "        batch_y = pad_sequences(test_Y[i : index], padding='post')\n",
    "        feed = {model.X: batch_x,\n",
    "                model.Y: batch_y,}\n",
    "        accuracy, loss = sess.run([model.accuracy,model.cost],\n",
    "                                    feed_dict = feed)\n",
    "\n",
    "        test_loss.append(loss)\n",
    "        test_acc.append(accuracy)\n",
    "        pbar.set_postfix(cost = loss, accuracy = accuracy)\n",
    "    \n",
    "    print('epoch %d, training avg loss %f, training avg acc %f'%(e+1,\n",
    "                                                                 np.mean(train_loss),np.mean(train_acc)))\n",
    "    print('epoch %d, testing avg loss %f, testing avg acc %f'%(e+1,\n",
    "                                                              np.mean(test_loss),np.mean(test_acc)))"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [],
   "source": [
    "from tensor2tensor.utils import bleu_hook"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "100%|██████████| 40/40 [00:38<00:00,  1.04it/s]\n"
     ]
    }
   ],
   "source": [
    "results = []\n",
    "for i in tqdm.tqdm(range(0, len(test_X), batch_size)):\n",
    "    index = min(i + batch_size, len(test_X))\n",
    "    batch_x = pad_sequences(test_X[i : index], padding='post')\n",
    "    feed = {model.X: batch_x}\n",
    "    p = sess.run(model.fast_result,feed_dict = feed)\n",
    "    result = []\n",
    "    for row in p:\n",
    "        result.append([i for i in row if i > 3])\n",
    "    results.extend(result)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "rights = []\n",
    "for r in test_Y:\n",
    "    rights.append([i for i in r if i > 3])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "0.065290846"
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "bleu_hook.compute_bleu(reference_corpus = rights,\n",
    "                       translation_corpus = results)"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.8"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
